package com.example.bootwithmybatis.service.impl;

import com.example.bootwithmybatis.entity.User;
import com.example.bootwithmybatis.mapper.UserMapper;
import com.example.bootwithmybatis.service.TestService;
import javafx.application.Application;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApplicationContext context;

    private TestService proxy;

    @PostConstruct
    public  void  init(){
        proxy = context.getBean(TestService.class);
    }


    @Override
    @Transactional
    public void parent() {
        User parent = new User();
        parent.setUserName("张大壮 Parent");
        parent.setPassWord("123");
        parent.setRealName("张壮");
        userMapper.insertUser(parent);
        //在parent里面调用child
        //1、直接调用
        try {
            child();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2、改为代理调用
        //((TestServiceImpl)AopContext.currentProxy()).child();
        //3.上下文进行解决
        //proxy.child();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void child() {
        User child = new User();
        child.setUserName("张大壮 child");
        child.setPassWord("654123");
        child.setRealName("张壮 child");
        userMapper.insertUser(child);
        throw new RuntimeException("child Exception..........");
    }


}
